package org.dormi.learn.product.application.material;

import org.dormi.learn.event.EventStore;
import org.dormi.learn.product.domain.material.action.CreateMaterialAction;
import org.dormi.learn.product.domain.material.entity.Material;
import org.dormi.learn.utils.Assert;
import org.springframework.transaction.annotation.Transactional;

/**
 * add description here
 *
 * @author : dormi330
 * @version : 1.0
 */
public class MaterialCreateCmd {

    private EventStore eventStore;

    public MaterialCreateCmd(EventStore eventStore) {
        Assert.isNotNull(eventStore, "不能为null: eventStore");
        this.eventStore = eventStore;
    }

    @Transactional
    public MaterialDTO createMaterial(MaterialCreateInDTO dto) {
        Material m = MaterialAssembler.MAPPER.toEO(dto);
        CreateMaterialAction action = new CreateMaterialAction(m);
        action.process();

        /* fail handle */
        /* fail handle */
        /* fail handle */
        if (action.getExp() != null) {
            throw action.getExp();
        }

        /* success handle */
        /* success handle */
        /* success handle */
        eventStore.saveList(action.getEvents());

        MaterialDTO result = MaterialAssembler.MAPPER.toDTO(m);
        return result;
    }
}
